package com.allwees.support.fileservice.upload;

import com.allwees.bs.core.modelbase.vo.R;
import com.allwees.support.fileservice.FileException;
import com.allwees.support.fileservice.config.FileConfig;
import com.allwees.support.fileservice.model.FileSummary;
import com.allwees.support.fileservice.req.UploadFileReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 文件上传Controller
 *
 * @author yangylsky
 */
@RestController
@RequestMapping("/api/v2/upload")
@Slf4j
public class UploadFileController {

    @Autowired
    private FileConfig config;

    /**
     * 上传文件
     *
     * @return
     */
    @PostMapping(value = "file", headers = "content-type=multipart/*")
    public R uploadFile(UploadFileReq req) {

        AliossBucketEnum bucketEnum = AliossBucketEnum.getEnum(req.getTypeCode());
        String bucket = bucketEnum.getBucket();
        BucketInfo bucketInfo = new BucketInfo(bucketEnum);
        try {
            UploadFileInfo uploadFileInfo = new UploadFileInfo(req.getFiledata().getInputStream(), req.getFilename(), req.getDescription(), req.getIsImage());
            FileSummary fileSummary;
            if (bucketEnum.isUser()) {
                fileSummary = UploadFileUtil.uploadUserFile(uploadFileInfo, bucketInfo);
            } else if (config.isTempBucket(bucket)) {
                fileSummary = UploadFileUtil.uploadTempFile(uploadFileInfo);
            } else if (config.isSysBucket(bucket)) {
                fileSummary = UploadFileUtil.uploadSysFile(uploadFileInfo, bucketInfo);
            } else if (config.isBsBucket(bucket)) {
                fileSummary = UploadFileUtil.uploadBsFile(uploadFileInfo, bucketInfo);
            } else {
                throw new FileException("未匹配配置的bucket: " + bucket);
            }
            return R.ok("上传成功", fileSummary);
        } catch (Exception e) {
            log.error("上传失败！", e);
            return R.error("上传失败");
        }
    }
}
